package com.cjhstudy.mall.service.impl;

import com.cjhstudy.mall.dao.UserMapper;
import com.cjhstudy.mall.enums.ResponseEnum;
import com.cjhstudy.mall.enums.RoleEnum;
import com.cjhstudy.mall.pojo.User;
import com.cjhstudy.mall.service.IUserService;
import com.cjhstudy.mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author: phil
 * @ProjectName: mall
 * @Date: 2021/12/8
 */
@Service
public class IUserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 注册
     * @param user
     */
    @Override
    public ResponseVo<User> register(User user) {
        //username 不能重复
        int countByUsername = userMapper.countByUsername(user.getUsername());
        if (countByUsername > 0){
            return ResponseVo.error(ResponseEnum.USERNAME_EXIT);
        }
        //email 不能重复
        int countByeEmail = userMapper.countByeEmail(user.getEmail());
        if (countByeEmail > 0){
            return ResponseVo.error(ResponseEnum.EMAIL_EXIT);
        }

        user.setRole(RoleEnum.CUSTOMER.getCode());

        //MD5摘要 -- 加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        //写入数据库
        int resultCount = userMapper.insertSelective(user);
        if (resultCount == 0){
            return ResponseVo.error(ResponseEnum.ERROR);
        }

        return ResponseVo.success();
    }

    @Override
    public ResponseVo<User> login(String username, String password) {
        //通过用户名查数据
        User user = userMapper.selectByUsername(username);
        //判断用户是否存在
        if (user == null){
            //用户不存在
            return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        //比较密码（返回用户名或密码错误）
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))){
           //密码不正确
            return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        user.setPassword(""); //返回的时候把密码给抹掉，不返回给前端显示
        //条件都成立的话，返回成功
        return ResponseVo.success(user);
    }
}
